package com.study.webapp.jdk8;


public class ThreadOrder2 {

    private  int flag = 1;


    public synchronized void first (String str) throws InterruptedException{
        while (flag % 3 != 1) {
            wait();
        }
        System.out.println(str);
        flag++;
        notifyAll();
    }

    public synchronized void second(String str) throws InterruptedException {
        while (flag % 3 != 2) {
            wait();
        }
        System.out.println(str);
        flag++;
        notifyAll();
    }
    public synchronized void third(String str) throws InterruptedException {
        while (flag % 3 != 0) {
            wait();
        }
        System.out.println(str);
        System.out.println("==============");
        flag++;
        notifyAll();
    }

    public static void main(String[] args) {
        ThreadOrder2 threadOrder = new ThreadOrder2();
        new Thread(() ->{
            try {
                for (int i = 0; i<10; i++) {
                    Thread.sleep(500);
                    threadOrder.second("B");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() ->{
            try {
                for (int i = 0; i<10; i++) {
                    threadOrder.first("A");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() ->{
            try {
                for (int i = 0; i<10; i++) {
                    threadOrder.third("C");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

